<?php
/**
 * 『过桥』 --  红鲤鱼与绿鲤鱼与驴屡屡 小组（何智权、曾志乐、钟荣林）
 */
class BridgeController extends Controller
{
    /**
     * 首页 - 已授权
     */
    public function actionIndex(){
        $wechatInfo = $this->_scope();
        // echo '<img src="' . $wechatInfo['img'] . '">';
        $this->smartyRender("index.html");
    }

    /**
     * 首页 - 未授权
     */
    public function actionScope(){
        if (isset($_GET['code'])){
            $code   = $_GET['code'];
            $appid  = "wx21a1e5ebdf092c50";
            $appsecret = "653efc869f436db4337a0ef7bfb1c539";
            
            $accessToken = AccessToken::getInstance("gh_cacd919e5b5c");
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
            $sendInfo = json_decode(Yii::app()->curl->get($url));
            
            if(isset($sendInfo->errcode) && $sendInfo->errcode != 0){
                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
                $sendInfo = json_decode(Yii::app()->curl->get($url));
            }
            @$openID = $sendInfo->openid;
            @$token  = $sendInfo->access_token;
            
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openID&lang=zh_CN";
            $sendInfo = json_decode(Yii::app()->curl->get($url));
            
            $img  = $sendInfo->headimgurl;
            $name = $sendInfo->nickname;
            
            // $_SESSION['openID'] = $openID; //openID保存在SESSION中
            setcookie("openID", $openID, time()+3600*24*7, "/", '.yikuaiqu.com');

            $BridgeService = BridgeService::getInstance();
            $BridgeService->saveWechatInfo($openID, $name, $img);

            $this->smartyRender("index.html");
        }else{
            exit('<h3>请在微信客户端打开</h3>');
        }
    }

    /**
     * 保存微信用户游戏得分
     */
    public function actionGameover(){
        if( Yii::app()->request->isAjaxRequest ){
            // $wechatInfo = $this->scope();
            // $openID = $wechatInfo['openID'];
            if(!isset($_COOKIE['openID']) || !isset($_POST['score'])) return false;
            $openID = $_COOKIE['openID'];
            $score = 0 + $_POST['score'];
            // $openID = isset($_COOKIE['openID']) && $_COOKIE['openID'] > '' ? $_COOKIE['openID'] : NULL;
            // $score  = isset($_POST['score']) && $_POST['score'] > 0 ? (int)$_POST['score'] : 0;
            if( empty($openID) ){
                $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx21a1e5ebdf092c50&redirect_uri=http%3a%2f%2fdev-m.game.yikuaiqu.com%2findex.php%3fr%3dbridge%2fscope&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
                header("Location:" . $url);
                exit;
            }

            $BridgeService = BridgeService::getInstance();
            $BridgeService->saveScore($openID, $score);
        }else{
            Tool::errorMessage("请求出错");
        }
    }

    /**
     * 获取所有用户的排名
     */
    public function actionAllRank(){
        // if( Yii::app()->request->isAjaxRequest ){
            $length = isset($_GET['length']) && $_GET['length'] > 0 && $_GET['length'] < 50 ? (int)$_GET['length'] : 10;
            // $wechatInfo = $this->scope();
            // $openID = $wechatInfo['openID'];
            // $openID = isset($_COOKIE['openID']) && $_COOKIE['openID'] > '' ? $_COOKIE['openID'] : '';
            // if( empty($openID) ){
            //     $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx21a1e5ebdf092c50&redirect_uri=http%3a%2f%2fdev-m.game.yikuaiqu.com%2findex.php%3fr%3dbridge%2fscope&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
            //     header("Location:" . $url);
            //     exit;
            // }

            $BridgeService = BridgeService::getInstance();
            $allRank       = $BridgeService->getAllRank($length);
            $rankID        = 1; 
            foreach ($allRank as $val) {
                $list[] = array(
                    'id'    => $rankID++,
                    'name'  => $val['fdName'],
                    // 'img'   => $val['fdImg'],
                    'score' => $val['fdTopScore']
                );
            }
            Tool::rightMessage($list);
        // }else{
        //     Tool::errorMessage("请求出错");
        // }
    }

    /**
     * 判断用户授权微信，如果有则获取数据库中的信息，如果没有则进入授权页
     * @return array
     */
    private function _scope(){
        // $openID = isset($_SESSION['openID']) && $_SESSION['openID'] > '' ? $_SESSION['openID'] : NULL;
        $openID = isset($_COOKIE['openID']) && $_COOKIE['openID'] > '' ? $_COOKIE['openID'] : NULL; 
        //如果没有获取到SESSION中的openID则跳转到授权页
        if( empty($openID) ){
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx21a1e5ebdf092c50&redirect_uri=http%3a%2f%2fdev-m.game.yikuaiqu.com%2findex.php%3fr%3dbridge%2fscope&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
            header("Location:" . $url);
            exit;
        }
        
        $BridgeService = BridgeService::getInstance();
        $wechatInfo    = $BridgeService->getWechatInfo($openID);
        
        if(!empty($wechatInfo)){
            return array(
                'openID' => $openID,
                'name'   => $wechatInfo['fdName'],
                'img'    => $wechatInfo['fdImg']
            );
        }

    }

}